package com.example.myapplication


import com.example.myapplication.base.DeviceNameActionSheetEvent
import com.example.myapplication.base.LanguageActionSheetEvent
import com.example.myapplication.base.NavBar
import com.example.sihookuiklydemo.base.BasePager
import com.example.sihookuiklydemo.base.MsgDialog
import com.example.sihookuiklydemo.base.NotifyName.Companion.DEVICE_HEIGHT
import com.example.sihookuiklydemo.base.NotifyName.Companion.DEVICE_NAME
import com.example.sihookuiklydemo.base.ProgressDialog
import com.example.sihookuiklydemo.bean.CustomDeskModeJson
import com.example.sihookuiklydemo.ble.getNewFloatPx
import com.example.sihookuiklydemo.net.Api.Companion.baseUrl
import com.example.sihookuiklydemo.theme.ThemeManager
import com.example.sihookuiklydemo.utils.getCancelText
import com.example.sihookuiklydemo.utils.getConfirmText
import com.example.sihookuiklydemo.utils.getLanguage
import com.tencent.kuikly.core.annotations.Page
import com.tencent.kuikly.core.base.Attr
import com.tencent.kuikly.core.base.Color
import com.tencent.kuikly.core.base.ViewBuilder
import com.tencent.kuikly.core.base.attr.ImageUri
import com.tencent.kuikly.core.directives.vfor
import com.tencent.kuikly.core.directives.vforIndex
import com.tencent.kuikly.core.directives.vif
import com.tencent.kuikly.core.log.KLog
import com.tencent.kuikly.core.module.CallbackRef
import com.tencent.kuikly.core.module.NetworkModule
import com.tencent.kuikly.core.module.NotifyModule
import com.tencent.kuikly.core.module.RouterModule
import com.tencent.kuikly.core.module.SharedPreferencesModule
import com.tencent.kuikly.core.nvi.serialization.json.JSONArray
import com.tencent.kuikly.core.nvi.serialization.json.JSONObject
import com.tencent.kuikly.core.reactive.handler.observable
import com.tencent.kuikly.core.reactive.handler.observableList
import com.tencent.kuikly.core.timer.setTimeout
import com.tencent.kuikly.core.views.ActionButtonTitleAttr
import com.tencent.kuikly.core.views.AlertDialog
import com.tencent.kuikly.core.views.Image
import com.tencent.kuikly.core.views.List
import com.tencent.kuikly.core.views.Modal
import com.tencent.kuikly.core.views.Text
import com.tencent.kuikly.core.views.TextAreaAttr
import com.tencent.kuikly.core.views.TextAttr
import com.tencent.kuikly.core.views.TextView
import com.tencent.kuikly.core.views.View
import com.tencent.kuikly.core.views.compose.Button

@Page("Setting")
internal class SettingPage : BasePager() {
    private var list by observableList<String>()
    var showAlert by observable(false)
    var showDeviceNameDialog by observable(false)
    var deviceName by observable("D07智能电动桌")
    var showProgressDialog by observable(false)
    lateinit var devcieUnbindbackRef: CallbackRef

    override fun created() {
        super.created()
        list.add(getLanguage("desk_mode_setting", "模式设置"))
        list.add(getLanguage("desk_issue", "故障说明"))
        list.add(getLanguage("device_device_name", "设备名称"))
        list.add(getLanguage("device_about_devices", "关于设备"))
        var pageJson = pagerData.params
        KLog.i("deviceinfo", "$pageJson")
        acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME).getString(
            DEVICE_NAME)?.let {
            deviceName = it
        }
        pageJson?.let {
            var darkMode = it.optInt("NightMode")
            KLog.i("深色模式", "${darkMode} ")
            var deviceInfo = it?.optJSONObject("bindDeviceInfo")

            /*deviceInfo?.let {
                it.optString("nameV2")?.let {
                    deviceName = it
                }
                KLog.i("deviceinfoJson", "$it")
            }*/
        }
        devcieUnbindbackRef =
            acquireModule<NotifyModule>(NotifyModule.MODULE_NAME).addNotify("DeviceUnbind") { data ->
                acquireModule<RouterModule>(RouterModule.MODULE_NAME).closePage()
            }

    }

    override fun pageWillDestroy() {
        super.pageWillDestroy()
        acquireModule<NotifyModule>(NotifyModule.MODULE_NAME).removeNotify(
            "DeviceUnbind",
            devcieUnbindbackRef
        )

    }

    override fun body(): ViewBuilder {
        val ctx = this
        return {

            NavBar {
                attr {
                    title = ctx.titleName ?: "更多设置"
                    rightIconShow = false
                    isDarkMode = ctx.isNightMode()
                }
                event {
                    onClick {

                        ctx.acquireModule<RouterModule>(RouterModule.MODULE_NAME).closePage()

                    }

                }
            }
            attr {
                backgroundColor(ctx.theme.colors.background)
            }
            View {
                attr {
                    marginTop(getNewFloatPx(18f))
                    backgroundColor(ctx.theme.colors.background)
                    height(1f)
                }
            }
            vforIndex({ ctx.list }) { item, index, _ ->
                View {

                    View {
                        attr {
                            flexDirectionRow()
                            alignItemsCenter()
                            backgroundColor(ctx.theme.colors.background)
                            width(ctx.pagerData.pageViewWidth)
                            minHeight(getNewFloatPx(60f))
                        }
                        event {
                            click {
                                var pageName = when (index) {
                                    0 -> "ModeSetting"
                                    1 -> "Issue"
                                    2 -> {

                                        ctx.showDeviceNameDialog = true
                                        ""
                                    }

                                    else -> "DeviceInfo"
                                }
                                if (pageName.isEmpty()) {

                                } else {
                                    ctx.openNameWithTitle(pageName, item)
                                    /*ctx.acquireModule<RouterModule>(RouterModule.MODULE_NAME)
                                        .openPage(pageName, ctx.pagerData.params)*/
                                }

                            }
                        }
                        Text {
                            attr {
                                margin(left = getNewFloatPx(16f))
                                fontSize(getNewFloatPx(15f))
                                text(item)
                                color(ctx.theme.colors.mainTextColor)
                                useDpFontSizeDim(true)
                            }
                        }
                        View { attr { flex(1f) } }
                        vif({ index == 2 }) {
                            Text {
                                attr {
                                    maxWidth(100f)
                                    text(ctx.deviceName)
                                    marginTop(8f)
                                    marginBottom(8f)
                                    //text("sssssssssssssssssssssssssssssss")
                                    useDpFontSizeDim(true)
                                    fontSize(getNewFloatPx(15f))
                                    color(ctx.theme.colors.mainTextColor)
                                }
                            }
                        }
                        Image {
                            attr {

                                size(getNewFloatPx(16f), getNewFloatPx(16f))
                                margin(right = getNewFloatPx(16f))
                                resizeContain()

                                if (ctx.isNightMode()) {
                                    tintColor(Color.WHITE)
                                }
                                src(ImageUri.commonAssets("ic_setting_arrow.png"))
                            }
                        }

                    }
                    View {
                        attr {
                            backgroundColor(ctx.theme.colors.grey_2)
                            height(1f)
                        }
                    }
                }


            }
            vif({ ctx.showDeviceNameDialog }) {
                Modal {
                    DeviceNameActionSheetEvent {
                        attr {
                            deviceName = ctx.deviceName
                            nameTag = ctx.getLanguage("device_device_name", "设备名称")
                        }
                        event {
                            // onRightClick { ctx.showDeviceNameDialog = false }
                            onCancelClick {
                                ctx.showDeviceNameDialog = false

                            }
                            onConfirmClick {
                                ctx.showDeviceNameDialog = false
                                ctx.deviceName = it
                                ctx.updateDeviceName(it)
                                KLog.i("deviceName", "$it")
                            }
                        }
                    }
                }
            }

            Button {
                attr {
                    size(ctx.pagerData.pageViewWidth - getNewFloatPx(48f), getNewFloatPx(48f))
                    backgroundColor(ctx.theme.colors.grey_1a)
                    titleAttr {
                        //text("解除绑定")
                        text(ctx.getLanguage("device_unbind", "解除绑定"))

                        fontSize(getNewFloatPx(15f))
                        color(Color.RED)
                        useDpFontSizeDim(true)
                    }
                    positionAbsolute()
                    borderRadius(getNewFloatPx(24f))
                    left(getNewFloatPx(24f))
                    right(getNewFloatPx(24f))
                    bottom(getNewFloatPx(44f))
                    highlightBackgroundColor(Color(Color.parseString16ToLong("0x644B4C4D")))
                }
                event {
                    click {
                        ctx.showAlert = true
                    }
                }
            }
            MsgDialog {
                attr {
                    showAlert(ctx.showAlert)
                    title(getLanguage("device_desk_unbind_warning","解除绑定后无法继续使用app控制电动桌，确定解绑？"))
                    actionButtons(getCancelText(), getConfirmText())


                }
                event {
                    clickActionButton { index ->
                        // 根据index进行确认点击了哪一个button处理对应事件(index值和actionButtons传入button的下标一致)
                        ctx.showAlert = false  // 关闭Alert弹框
                        if (index == 1) {
                            ctx.unBindDevice()
                        }
                    }
                    willDismiss {
                        // 按下系统返回按键或右滑返回时触发
                        ctx.showAlert = false  // 关闭Alert弹框
                    }
                }
            }
            vif({ ctx.showProgressDialog }) {
                Modal {
                    ProgressDialog { }
                }
            }
        }
    }

    fun unBindDevice() {

        //acquireModule<RouterModule>(RouterModule.MODULE_NAME).closePage()
        showProgressDialog = true
        var pageJson = pagerData.params
        pageJson?.let {
            var token = it.optString("token")
            var userId = it.optInt("userId")
            var eqId = it.optInt("equipmentId")
            var jsonObject = JSONObject()
            jsonObject.put("equipmentId", eqId)
            jsonObject.put("token", token)
            jsonObject.put("userId", userId)
            jsonObject.put("isNeedPush", true)
            jsonObject.put("isPull", false)
            var jsonObjectHeader = JSONObject()
            jsonObjectHeader.put("Content-Type", "application/json")
            acquireModule<NetworkModule>(NetworkModule.MODULE_NAME).httpRequest(
                "${baseUrl}app/equipment/binding/unbindEquipment",
                true,
                jsonObject,
                headers = jsonObjectHeader,
                responseCallback = { data, success, errorMsg, networkResponse ->
                    var content = data.optJSONObject("content")
                    var code = data.optInt("code")

                    if (code == 0) {
                        sendCloseNotify()
                        //sendCloseNotify()


                        //     acquireModule<RouterModule>(RouterModule.MODULE_NAME).closePage()


                        /*  toastMsg="更新模式成功"
                          showMsgDialog=true*/
                    } else {
                        showProgressDialog = false
                    }

                    KLog.i("ss", "${data.toString()} $success $errorMsg $networkResponse")
                })
        }
    }

    fun updateDeviceName(deviceName: String) {
        showProgressDialog = true
        var pageJson = pagerData.params
        pageJson?.let {
            var token = it.optString("token")
            var userId = it.optInt("userId")
            var eqId = it.optInt("equipmentId")
            var jsonObject = JSONObject()
            jsonObject.put("equipmentId", eqId)
            jsonObject.put("token", token)
            jsonObject.put("userId", userId)
            jsonObject.put("name", deviceName)
            jsonObject.put("nameV2", deviceName)
            var jsonObjectHeader = JSONObject()
            jsonObjectHeader.put("Content-Type", "application/json")
            acquireModule<NetworkModule>(NetworkModule.MODULE_NAME).httpRequest(
                "${baseUrl}app/equipment/info/update",
                true,
                jsonObject,
                headers = jsonObjectHeader,
                responseCallback = { data, success, errorMsg, networkResponse ->
                    var content = data.optJSONObject("content")
                    var code = data.optInt("code")
                    showProgressDialog = false
                    if (code == 0) {
                        var jsonObject = JSONObject()
                        jsonObject.put("equipmentId", eqId)
                        jsonObject.put("nameV2", deviceName)
                        sendUpdateDeviceInfo(jsonObject)
                        saveDeviceName(deviceName)
                        /*  toastMsg="更新模式成功"
                          showMsgDialog=true*/
                    }

                    KLog.i("ss", "${data.toString()} $success $errorMsg $networkResponse")
                })
        }
    }

    fun sendCloseNotify() {
        acquireModule<NotifyModule>(NotifyModule.MODULE_NAME).postNotify(
            "DeviceUnbind",
            JSONObject()
        )
    }

    fun sendUpdateDeviceInfo(jsonObject: JSONObject) {
        acquireModule<NotifyModule>(NotifyModule.MODULE_NAME).postNotify(
            "UpdateDeviceInfo",
            jsonObject
        )
    }

    fun saveDeviceName(name: String) {
        acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)
            .setString(DEVICE_NAME, name)
    }
}